"use client"

import { Doc } from "@/convex/_generated/dataModel"
import { IconPicker } from "./icon-picker"
import { Button } from "@/components/ui/button"
import { ImageIcon, Smile, X } from "lucide-react"
import { ElementRef, useRef, useState } from "react"
import { useMutation } from "convex/react"
import { api } from "@/convex/_generated/api"
import TextareaAutosize from 'react-textarea-autosize'
import { useCoverImage } from "@/hooks/use-cover-images"

interface ToolbarProps {
    initialData: Doc<"documents">,
    preview?: boolean
}
export const Toolbar = ({ initialData, preview }: ToolbarProps) => {
    const inputRef = useRef<ElementRef<"textarea">>(null)
    const [isEditing, setIsEditing] = useState(false)
    const [value, setValue] = useState(initialData.title)
    const update = useMutation(api.documents.update)
    const removeIcon = useMutation(api.documents.removeIcon)

    const coverImage = useCoverImage()



    const enableInput = () => {
        if (preview) return
        setIsEditing(true)
        setTimeout(() => {
            setValue(initialData.title)
            inputRef.current?.focus()
        }, 0)
    }
    const disableInput = () => setIsEditing(false)

    const onInput = (value: string) => {
        setValue(value)
        update({ id: initialData._id, title: value || "Untitled" })
    }

    // 回车保存
    const onkeyDown = (event: React.KeyboardEvent<HTMLTextAreaElement>) => {
        if (event.key === 'Enter') {
            event.preventDefault()
            disableInput()
        }
    }

    const onIconSelect = (icon: string) => {
        update({ id: initialData._id, icon })
    }

    const onRemove = () => {
        removeIcon({ id: initialData._id })
    }

    return (<div className="pl-[54px] group relative">
        <div className="flex flex-row items-center py-4">
            {!!initialData.icon && !preview && (
                <div className="flex items-center gap-x-2 group/icon">
                    <IconPicker onChange={onIconSelect}>
                        <p className="text-6xl hover:opacity-75 transition">{initialData.icon}</p>
                    </IconPicker>
                    <Button
                        onClick={onRemove}
                        variant={"outline"}
                        size={"icon"}
                        className="rounded-full opacity-0 group-hover/icon:opacity-100 transition text-muted-foreground">
                        <X className="h-4 w-4" />
                    </Button>
                </div>
            )}
            {!!initialData.icon && preview && (
                <p className="text-6xl pt-6">
                    {initialData.icon}
                </p>
            )}
            <div className="opacity-0 group-hover:opacity-100 flex items-center gap-x-1 py-4">
                {!initialData.icon && !preview && (<>
                    <IconPicker onChange={onIconSelect}>
                        <Button className="text-xs text-muted-foreground" size={"sm"} variant={"outline"}>
                            <Smile className="h-4 w-4 mr-2" />
                            Add Icon
                        </Button>
                    </IconPicker>
                </>)}
            </div>
            <div className="opacity-0 group-hover:opacity-100 ml-4 flex items-center gap-x-1 py-4">
                {!initialData.coverImage && !preview && (<>
                    <Button onClick={coverImage.onOpen} className="text-xs text-muted-foreground" size={"sm"} variant={"outline"}>
                        <ImageIcon className="h-4 w-4 mr-2" />
                        Add Cover
                    </Button>
                </>)}
            </div>
        </div>
        {isEditing && !preview ? (<>
            <TextareaAutosize
                ref={inputRef}
                onBlur={disableInput}
                onKeyDown={onkeyDown}
                value={value}
                onChange={(e) => onInput(e.target.value)}
                className="text-5xl bg-transparent font-bold break-words outline-none text-[#CFCFCF]"

            />
        </>) : (<div onClick={enableInput} className="pb-[11.5px] text-5xl font-bold break-words outline-none">
            {initialData.title}
        </div>)}
    </div>)
}